package com.bawan.vims.common;

/**
 * 
 * <p> Description	: IDGenerator.java </p>
 * <p> Copyright	: Copyright (c) 2015 by FITT</p>
 * <p> Author 		: ZCC </p>
 * <p> Create		: 2015年2月7日 下午4:47:19 </p> 
 * <p> version 		: 1.0 </p>
 */
public class IDGenerator {
	
	//计数器从0到99,以保证同一毫秒可产生100个不同的唯一的随机数
	private static int counter = 0;

	/**
	 * 让计数器加1
	 * @return
	 */
	private static synchronized int add() {
		if (counter == 99999)
			counter = -1;
		return ++counter;
	}

	/**
	 * 让计数器加1并且以String类型返回,如果counter<10,则在其前加"0"再返回
	 * @return
	 */
	private static synchronized String getStrOfAdd() {
		int tempAdd = add();
		if (tempAdd < 10)
			return "0000" + String.valueOf(tempAdd);
		else if(tempAdd<100)
			return "000" + String.valueOf(tempAdd);
		else if(tempAdd<1000)
			return "00" + String.valueOf(tempAdd);
		else if(tempAdd<10000)
			return "0" + String.valueOf(tempAdd);
		else
			return String.valueOf(tempAdd);
	}

	/**
	 * 跟据给出的唯一键的长度返回一个SessionID,长度不小于13(系统时间长度)
	 * @param length
	 * @return
	 */
	public static String getIDByCurrentTime(int length) {
		String currentTime = String.valueOf(System.currentTimeMillis());
		String tempCount = getStrOfAdd();
		if (length > 13) { //当指定长度大于系统时间长度
			int extra = length - 13;
			switch (extra) {
			case 1: //length=14
				return currentTime + tempCount.substring(tempCount.length()-1);
			case 2: //length=15
				return currentTime + tempCount.substring(tempCount.length()-2);
			case 3: //length=16
				return currentTime + tempCount.substring(tempCount.length()-3);
			case 4: //length=17
				return currentTime + tempCount.substring(tempCount.length()-4);
			case 5: //length=18
				return currentTime + tempCount;
			default://length>=19
				String zero = "";
				for (int i = 0; i < length - 18; i++)
					zero += "0";
				return currentTime + zero + tempCount;
			}
		} else {
			String zero="";
			int l=tempCount.length();
			for (int i = 0; i < length - l; i++)
				zero += "0";
			return zero+tempCount;
		}
	}
	
	public static String getID(int length) {
		String tempCount = getStrOfAdd();
		String zero="";
		int l=tempCount.length();
		for (int i = 0; i < length - l; i++)
			zero += "0";
		return zero+tempCount;
	}

	public static void main(String args[]) {

		
		for(int i=0;i<1000;i++)
		{
			String id=IDGenerator.getID(10);
			System.out.println(id+"-->"+id.length());
		}
	}
}
